package com.huang.crawler.util;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * @ClassName:CommonUtils.java
 * @ClassDescribe:常用工具
 * @createPerson:huangying
 * @createDate:2018年7月26日 下午1:59:38
 * @version
 */
public class CommonUtils {

	/**
	 * 
	 * @ClassDescribe:将流转为字符串
	 * @auth:huangying
	 * @createDate:2018年7月26日 下午1:59:08
	 * @param is
	 *            输入流
	 * @return 返回字符串结果
	 */
	public static String readInputStream(InputStream is) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int length = 0;
			byte[] buffer = new byte[1024];
			while ((length = is.read(buffer)) != -1) {
				baos.write(buffer, 0, length);
			}
			is.close();
			baos.close();
			// 或者用这种方法
			// byte[] result=baos.toByteArray();
			// return new String(result);
			return baos.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * @ClassDescribe:根据链接下载图片
	 * @auth:huangying
	 * @createDate:2018年7月26日 下午3:04:34
	 * @param imgUrl
	 * @param path
	 */
	public static void downloadPicture(List<String> urlList, String paperFilaName) {
		URL url = null;
		File baiduImgFile = new File("C:/百度图片");
		createFile(baiduImgFile);
		String filePath = baiduImgFile.getAbsolutePath() + "/" + paperFilaName;
		createFile(new File(filePath));
		Iterator<String> iterator = urlList.iterator();
		while (iterator.hasNext()) {
			try {
				String imgUrl = iterator.next();
				String image = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
				url = new URL(imgUrl);
				DataInputStream dataInputStream = new DataInputStream(url.openStream());
				FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath + "/" + image));
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int length;
				while ((length = dataInputStream.read(buffer)) > 0) {
					output.write(buffer, 0, length);
				}
				fileOutputStream.write(output.toByteArray());
				fileOutputStream.close();
				dataInputStream.close();
				iterator.remove();
			} catch (MalformedURLException e) {
				iterator.remove();
				downloadPicture(urlList, paperFilaName);
			} catch (IOException e) {
				iterator.remove();
				downloadPicture(urlList, paperFilaName);
			}
		}
	}

	/**
	 * 
	 * @ClassDescribe:文件不存在则生成文件
	 * @auth:huangying
	 * @createDate:2018年7月26日 下午3:23:59
	 * @param file
	 */
	public static void createFile(File file) {
		if (!file.exists()) {
			file.mkdir();
		}
	}
}